package com.bindingfly.client.formrender.widget.impl;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import com.bindingfly.client.formrender.WidgetInjecterPojo;
import com.bindingfly.client.formrender.widget.types.InjectableWidget;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.xml.client.Document;
import com.google.gwt.xml.client.Node;
import com.google.gwt.xml.client.XMLParser;
import com.google.gwt.xml.client.Element;

public class SubmitButtonFly implements InjectableWidget
{

	@Override
	public boolean doesRequirePostProcessExecution()
	{
		// TODO Auto-generated method stub 
		return true;
	}

	@Override
	public void executePostProcess(Widget widget, final HashMap<String, WidgetInjecterPojo> renderedWidgets)
	{
		Button submitButton = (Button)widget;
		submitButton.addClickHandler(new ClickHandler(){

			@Override
			public void onClick(ClickEvent event)
			{
				Set<Entry<String, WidgetInjecterPojo>> entryList = renderedWidgets.entrySet();
				
				Document document = XMLParser.createDocument();
				
				Element rootElement = document.createElement("requestModel");
				
				document.appendChild((Node)rootElement);
				
				for (Entry<String, WidgetInjecterPojo> entry: entryList)
				{
					WidgetInjecterPojo widgetInjecterPojo = entry.getValue();
					
					//TODO this doesn't submit things like tables.  but this is only a demo
					String value = widgetInjecterPojo.injectableWidget.getSubmitableValue(widgetInjecterPojo.widget);
					
					if (value != null)
					{
						Element dataValueElement = (Element) document.createElement("dataValue");
					
						dataValueElement.setAttribute("fieldName", entry.getKey());
						dataValueElement.setAttribute("value", value);
						rootElement.appendChild(dataValueElement);
					}
					
				}
				Window.alert(rootElement.toString());
				
			}});
	}

	@Override 
	public String getSubmitableValue(Widget widget)
	{
		return null;
	}

	@Override
	public Widget init(com.google.gwt.dom.client.Element seedElement)
	{
		Button submitButton = new Button();
		
		submitButton.setText("Submit");
		
		return submitButton;
	}

}
